package com.ejy.base.data.utils;

import com.ejy.commons.utils.StringUtils;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.io.IOUtils;
import org.springframework.http.MediaType;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.*;

/**
 * @author WangYan
 * @description:
 * @date 2021/10/12 16:13
 */
public class FileUtils {

    public static File multipartFileToFile(MultipartFile multipartFile) {
        //选择用缓冲区来实现这个转换即使用java 创建的临时文件 使用 MultipartFile.transferto()方法 。
        File file = null;
        try {
            String originalFilename = multipartFile.getOriginalFilename();
            String[] filename = originalFilename.split("\\.");
            file = File.createTempFile(filename[0], filename[1]);
            multipartFile.transferTo(file);
            file.deleteOnExit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return file;
    }

    public static MultipartFile fileToMultipartFile(File file) {
        if (file == null) {
            return null;
        }
        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.ALL_VALUE, true, file.getName());
        try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) {
            IOUtils.copy(input, os);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("文件 转 多媒体文件 失败 fileToMultipartFile: " + e);
        }
        MultipartFile multipartFile = new CommonsMultipartFile(fileItem);
        return multipartFile;
    }

    public static File inputStreamToFile(String filePrefix, String fileSuffix, InputStream inputStream) {
        File tempFile = null;
        if (StringUtils.isEmpty(filePrefix) || StringUtils.isEmpty(fileSuffix) || inputStream == null) {
            return tempFile;
        }
        try {
            byte[] buffer = new byte[inputStream.available()];
            inputStream.read(buffer);

            tempFile = File.createTempFile(filePrefix, fileSuffix);
            OutputStream outStream = new FileOutputStream(tempFile);
            outStream.write(buffer);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("流 转 文件 失败 inputStreamToFile: " + e);
        }
        return tempFile;
    }
}
